# !/usr/bin/env Python3
# -*- coding: utf-8 -*-
# 作者   : 王宗龙
# 文件     : user.py
# 时间     : 2020/12/9 15:30
# 开发工具 : PyCharm


from apps.base.log import logger,conf
import hashlib
import time
import jwt
from apps.models import Users,AccessRecords
from apps.base.db import session
from fastapi import Header, HTTPException,Request,APIRouter,Body
import time,datetime
route = APIRouter()

def md5value(s):
    md5 = hashlib.md5()
    md5.update(s)
    return md5.hexdigest()

@logger.catch()
@route.post("/login",summary='用户登录，获取TOKEN')
def login(username: str=Body(...), password: str=Body(...),):
    '''TOKEN 获取接口
    ============================
    '''
    user= session.query(Users).filter_by(name=username,passwd=md5value(password.encode())).first()
    logger.debug(user)
    if user:
        info={"id":user.id,"username":user.name,"nicename":user.nicename}
        payload = {
            "iat": int(time.time()),
            "exp": int(time.time()) + 86400 * 7,
            # token签发者
            'iss': 'zlWang',
            'data': info,
            "jti": "4f1g23a12aa"
        }
        # 生成token
        token = jwt.encode(payload, conf.SECRET_KEY, algorithm='HS512', )
        data = {"msg": "登录成功!", "token": token, "code": 1, "userinfo": info}
        user.lastlogin=datetime.datetime.now()
        session.add(user)
        # session.commit()
    else:
        data = {"msg": "登录失败!", "code": -1}
    return data

@logger.catch()
class User_info:
    def __init__(self,userid):
        self.USERID=userid

@logger.catch()
class CurrentUser:
    def __init__(self,request: Request ,TOKEN: str = Header(None) ,QTOKEN: str=None):
        if TOKEN or QTOKEN:
            tk=TOKEN if TOKEN else QTOKEN
            users = ''
            try:
                users = jwt.decode(tk, conf.SECRET_KEY, algorithms=['HS512'])
            except Exception as e:
                logger.error(e)
            if users:
                user = users['data']
                logger.debug(user)
                self.userid = user['id']
                self.username = user['username']
                self.nicename = user['nicename']
                # logger.debug(conf.access_records)
                if conf.access_records:
                    accessrecords=AccessRecords(userid=user['id'],username=user['username'], nicename=user['nicename'],url=str(request.url),method=request.method)
                    # logger.debug(accessrecords.nicename)
                    session.add(accessrecords)
                    # session.commit()
                return
        data = {"msg": "用户未登录!", "code": -1}
        raise HTTPException(status_code=200, detail=data)
